<template>
    <view class="vote-from">
        <text class="vote-from-title">
                解聘/选聘物业服务企业或者其他管理人
            </text>
        <!-- 多问题模式 - 使用voteOptionMap -->
        <view class="w-full" v-if="voteOptionMap && Object.keys(voteOptionMap).length > 0">
          
            <view class="vote-from-content" v-for="(options, questionTitle) in voteOptionMap" :key="questionTitle">
                <view class="vote-from-content-title">
                    {{ questionTitle }} 
                </view>
                <view class="vote-from-content-item">
                    <VoteFromItem
                        :isRevote="isRevote"
                        :optionId="item.optionId"
                        :isVotingInfo="isVotingInfo"    
                        :voteNum="item.voteNum"
                        :areaNum="item.areaNum"
                        v-for="(item, idx) in options"
                         :key="item.optionId"
                        :checked="isOptionSelected(item.optionId, questionTitle)"
                        :label="item.name"
                        :optionInfo="getQuestionOptionInfo(questionTitle)"
                        @change="handleSelect(idx, questionTitle)"
                    />
                </view>
            </view>
        </view>
        
        <!-- 多问题模式 - 使用groupedOptions -->
        <view class="w-full" v-else-if="groupedOptions && Object.keys(groupedOptions).length > 0">
          
            <view class="vote-from-content" v-for="(options, questionTitle) in groupedOptions" :key="questionTitle">
                <view class="vote-from-content-title u-flex">
                    {{ questionTitle }} 
                    <text class="selection-limit-hint" v-if="getQuestionSelectType(questionTitle) && shouldShowLimitHint(questionTitle)">
                        （{{ getLimitHintText(questionTitle) }}）
                    </text>
                    <u-icon @click="showLimitHint(questionTitle)" name="info-circle-fill" size="20" color="#999"></u-icon>    
                </view>
                <view class="vote-from-content-item">
                    <VoteFromItem
                        :isRevote="isRevote"
                        :optionId="item.optionId"
                        :isVotingInfo="isVotingInfo"    
                        :voteNum="item.voteNum"
                        :areaNum="item.areaNum"
                        v-for="(item, idx) in options"
                         :key="item.optionId"
                        :checked="isOptionSelected(item.optionId, questionTitle)"
                        :label="item.name"
                        :optionInfo="getQuestionOptionInfo(questionTitle)"
                        @change="handleSelect(idx, questionTitle)"
                    />
                </view>
               
                <!-- 问题相关附件 -->
                <Relatedaccessories 
                    v-if="getQuestionFileUrl(questionTitle)"
                    :fileUrl="getQuestionFileUrl(questionTitle)"
                />
            </view>
        </view>
        
        <!-- 单问题模式（兼容原有逻辑） -->
        <view v-else-if="voteOptions && voteOptions.length > 0">
            <view class="vote-from-content">
                <view class="vote-from-content-title">
                    <!-- 使用原有的标题或默认标题 -->
                </view>
                <view class="vote-from-content-item">
                    <VoteFromItem
                        :isRevote="isRevote"
                        :optionId="item.optionId"
                        :isVotingInfo="isVotingInfo"
                        :voteNum="item.voteNum"
                        :areaNum="item.areaNum"
                        v-for="(item, idx) in voteOptions"
                        :key="idx"
                        :checked="isRadio ? selectedIndex.includes(idx) : selectedIndex[0] === idx"
                        :label="item.name"
                        :optionInfo="optionInfo"
                        @change="handleSelectSingle(idx)"
                    />
                </view>
            </view>
        </view>
        
        <!-- 无数据状态 -->
        <view v-else class="no-data">
            暂无投票选项
        </view>
    </view>
</template>

<script>
import UIcon from '../../../uni_modules/uview-ui/components/u-icon/u-icon.vue'
import VoteFromItem from './VoteFromItem.vue'
import Relatedaccessories from './Relatedaccessories.vue'
export default {
    props:{
        value: {
            type: Array,
            default: () => []
        },
        voteOptions:{
            deep:true,
            type:Array,
            default:()=>[]
        },
        voteOptionMap:{
            deep:true,
            type:Object,
            default:()=>{}
        },
        optionInfo:{
            deep:true,
            type:Object,
            default:()=>{}
        },
               
        isVotingInfo:{
            immediate:true,
            deep:true,
            type:Object,
            default:()=>{}
        },
        isRevote:{
            type:Boolean,
            default:false
        },
        mobile:{
            type:String,
            default:''
        }
    },
    computed: {
        // 将voteOptions数组按title分组
        // groupedOptions() {
        //     const grouped = {}
        //     if (this.voteOptions && this.voteOptions.length > 0) {
        //         this.voteOptions.forEach(item => {
        //             const title = item.title || '未命名问题'
        //             if (!grouped[title]) {
        //                 grouped[title] = []
        //             }
        //             grouped[title].push(item)
        //         })
        //     }
        //     console.log("grouped",grouped)
        //     return grouped
        // }
        groupedOptions() {
            const grouped = {}
            if (this.voteOptions && this.voteOptions.length > 0) {
                this.voteOptions.forEach((item, index) => {
                    const title = item.title || '未命名问题'
                    if (!grouped[title]) {
                        grouped[title] = []
                    }
                    grouped[title].push(item)
                })
                
                // 为每个议题组添加 min/max 限制的 mock 数据
                const questionTitles = Object.keys(grouped)
                questionTitles.forEach((title, questionIndex) => {
                    const options = grouped[title]
                    
        
                    
                    // 为该议题下的所有选项添加相同的限制和文件URL
                    options.forEach(option => {
                        console.log("option",option)
                        option.min = option.minNum
                        option.max = option.maxNum
                        option.fileUrl = option.fileUrl
                    })
                })
            }
            console.log("grouped with mock data", grouped)
            return grouped
        }
    },
    watch:{
        // 移除value的watch，让组件自主管理状态
        // value: {
        //     handler(newVal) {
        //         this.syncFromValue(newVal)
        //     },
        //     deep: true,
        //     immediate: true
        // },
        isVotingInfo:{
            handler(newVal){
               // 只在isVotingInfo变化时初始化，且只在已投票状态下初始化
               if (newVal && newVal.isVoting) {
                   this.initSelectedOptions()
               }
            },
            deep:true,
            immediate:true
        },
        optionInfo:{
            handler(newVal){
                // 移除原有的voteRule判断逻辑，改为在具体选择时判断
            },
            deep:true,
            immediate:true
        },
        voteOptionMap:{
            handler(newVal, oldVal){
                // 只在voteOptionMap真正变化且不是从空变为有值时初始化
                if (newVal && Object.keys(newVal).length > 0 && 
                    (!oldVal || Object.keys(oldVal).length === 0)) {
                    this.initSelectedOptions()
                }
            },
            deep:true,
            immediate:true
        },
        voteOptions:{
            handler(newVal, oldVal){
                // 只在voteOptions真正变化且不是从空变为有值时初始化
                if (newVal && newVal.length > 0 && 
                    (!oldVal || oldVal.length === 0)) {
                    this.initSelectedOptions()
                }
            },
            deep:true,
            immediate:true
        }
    },
    components:{
        VoteFromItem,
        UIcon,
        Relatedaccessories
    },
    name: 'VoteFrom',
    data(){
        return {
            selectedOptionIds: [], // 存储选中的选项ID（多问题模式）
            selectedOptionsByQuestion: {}, // 按问题存储选中的选项（多问题模式）
            selectedIndex: [], // 存储选中的索引（单问题模式）
            isRadio:false //true为多选 false为单选（保留用于单问题模式）
        }
    },
    mounted() {
        // 延迟初始化，确保所有数据都已加载
        this.$nextTick(() => {
            this.initSelectedOptions()
        })
    },
    methods: {
        showLimitHint(questionTitle){
            // 从 groupedOptions 中获取该议题的 remark
            if (this.groupedOptions && this.groupedOptions[questionTitle]) {
                const options = this.groupedOptions[questionTitle]
                if (options && options.length > 0) {
                    const remark = options[0].remark
                    if (remark) {
                        uni.showToast({
                            icon:'none',
                            title: remark,
                            duration: 2000
                        })
                       
                        return
                    }
                }
            }
            
            // 如果没有 remark，显示默认提示
            uni.showModal({
                title: '选择规则',
                content: '请根据题目要求进行选择',
                showCancel: false,
                confirmText: '我知道了'
            })
        },
        clear(){
            this.selectedOptionIds = []
            this.selectedOptionsByQuestion = {}
            this.selectedIndex = []
        },
        // 从外部value同步内部状态
        syncFromValue(value) {
            // 如果外部value为空，不要清空内部状态，保持当前选择
            if (!value || !Array.isArray(value)) {
                return
            }
            
            // 如果value是空数组，也不要清空，保持当前选择
            if (value.length === 0) {
                return
            }
            
            // 多问题模式
            if ((this.voteOptionMap && Object.keys(this.voteOptionMap).length > 0) || 
                (this.groupedOptions && Object.keys(this.groupedOptions).length > 0)) {
                
                this.selectedOptionIds = value.map(item => String(item.optionId))
                this.selectedOptionsByQuestion = {}
                
                const optionMap = this.voteOptionMap && Object.keys(this.voteOptionMap).length > 0 ? 
                    this.voteOptionMap : this.groupedOptions
                
                // 将选中的选项ID按问题分类
                this.selectedOptionIds.forEach(optionId => {
                    Object.keys(optionMap).forEach(questionTitle => {
                        const options = optionMap[questionTitle] || []
                        const option = options.find(item => String(item.optionId) === optionId)
                        if (option) {
                            if (!this.selectedOptionsByQuestion[questionTitle]) {
                                this.$set(this.selectedOptionsByQuestion, questionTitle, [])
                            }
                            this.selectedOptionsByQuestion[questionTitle].push(optionId)
                        }
                    })
                })
            } 
            // 单问题模式
            else if (this.voteOptions && this.voteOptions.length > 0) {
                this.selectedIndex = value.map(item => 
                    this.voteOptions.findIndex(option => option.optionId == item.optionId)
                ).filter(idx => idx !== -1)
            }
        },
        // 判断某个问题的选择类型（单选/多选）
        getQuestionSelectType(questionTitle) {
            const optionMap = this.voteOptionMap && Object.keys(this.voteOptionMap).length > 0 ? 
                this.voteOptionMap : this.groupedOptions
            
            const options = optionMap[questionTitle] || []
            
            // 检查所有选项的optionType
            const optionTypes = options.map(item => item.optionType).filter(type => type !== null && type !== undefined)
            
            if (optionTypes.length > 0) {
                // 如果所有选项的optionType都相同，使用该类型
                const uniqueTypes = [...new Set(optionTypes)]
                if (uniqueTypes.length === 1) {
                    return uniqueTypes[0] === 2 // 2为多选，1为单选
                }
            }
            
            // 如果optionType都为null或不存在，回退到voteRule
            return this.optionInfo.voteRule == 2 || this.optionInfo.voteRule == 4
        },
        // 检查选项是否被选中（多问题模式）
        isOptionSelected(optionId, questionTitle) {
            // 如果是多选模式，使用全局选中数组
            const isMultiSelect = this.getQuestionSelectType(questionTitle)
            if (isMultiSelect) {
                return this.selectedOptionIds.includes(String(optionId))
            } else {
                // 如果是单选模式，只检查当前议题的选中选项
                const currentQuestionSelected = this.selectedOptionsByQuestion[questionTitle] || []
                return currentQuestionSelected.includes(String(optionId))
            }
        },
        // 获取每个问题的选项信息（包含该问题的总投票数）
        getQuestionOptionInfo(questionTitle) {
            // 优先使用voteOptionMap
            let options = []
            if (this.voteOptionMap && this.voteOptionMap[questionTitle]) {
                options = this.voteOptionMap[questionTitle]
            } else if (this.groupedOptions && this.groupedOptions[questionTitle]) {
                options = this.groupedOptions[questionTitle]
            }
            
            const questionTotalVoteNum = options.reduce((total, item) => total + Number(item.voteNum), 0)
            const questionTotalAreaNum = options.reduce((total, item) => total + Number(item.areaNum), 0)
            
            return {
                zongvoteNum: questionTotalVoteNum,
                zongvoteSize: questionTotalAreaNum,
                voteRule: this.optionInfo.voteRule
            }
        },
        // 初始化选中状态
        initSelectedOptions() {
            // 多问题模式初始化
            if ((this.voteOptionMap && Object.keys(this.voteOptionMap).length > 0) || 
                (this.groupedOptions && Object.keys(this.groupedOptions).length > 0)) {
                
                this.selectedOptionsByQuestion = {}
                const optionMap = this.voteOptionMap && Object.keys(this.voteOptionMap).length > 0 ? 
                    this.voteOptionMap : this.groupedOptions
                
                Object.keys(optionMap).forEach(questionTitle => {
                    this.$set(this.selectedOptionsByQuestion, questionTitle, [])
                })
                
                if (this.isVotingInfo.isVoting && this.isVotingInfo.optionId) {
                    // 处理已投票状态
                    let optionIds = this.isVotingInfo.optionId
                    if (Array.isArray(optionIds)) {
                        this.selectedOptionIds = optionIds.map(id => String(id))
                    } else {
                        this.selectedOptionIds = [String(optionIds)]
                    }
                    
                    // 将选中的选项ID按问题分类
                    this.selectedOptionIds.forEach(optionId => {
                        Object.keys(optionMap).forEach(questionTitle => {
                            const options = optionMap[questionTitle] || []
                            const option = options.find(item => String(item.optionId) === optionId)
                            if (option) {
                                if (!this.selectedOptionsByQuestion[questionTitle]) {
                                    this.$set(this.selectedOptionsByQuestion, questionTitle, [])
                                }
                                this.selectedOptionsByQuestion[questionTitle].push(optionId)
                            }
                        })
                    })
                } else {
                    this.selectedOptionIds = []
                }
            } 
            // 单问题模式初始化
            else if (this.voteOptions && this.voteOptions.length > 0) {
                // 判断单问题模式的选择类型
                const optionTypes = this.voteOptions.map(item => item.optionType).filter(type => type !== null && type !== undefined)
                if (optionTypes.length > 0) {
                    const uniqueTypes = [...new Set(optionTypes)]
                    if (uniqueTypes.length === 1) {
                        this.isRadio = uniqueTypes[0] === 2 // 2为多选，1为单选
                    } else {
                        this.isRadio = this.optionInfo.voteRule == 2 || this.optionInfo.voteRule == 4
                    }
                } else {
                    this.isRadio = this.optionInfo.voteRule == 2 || this.optionInfo.voteRule == 4
                }
                
                if (this.isVotingInfo.isVoting) {
                    let row = this.isVotingInfo.optionId
                    if (Array.isArray(row) && row.length > 1) {
                        this.selectedIndex = row.map(e => this.voteOptions.findIndex(item => item.optionId == e))
                    } else {
                        this.voteOptions.forEach((item, key) => {
                            if (item.optionId == this.isVotingInfo.optionId) {
                                this.selectedIndex = [key]
                            }
                        })
                    }
                } else {
                    this.selectedIndex = []
                }
            }
        },
        getSelectedIndex(){
            // 多问题模式
            if ((this.voteOptionMap && Object.keys(this.voteOptionMap).length > 0) || 
                (this.groupedOptions && Object.keys(this.groupedOptions).length > 0)) {
                let selectedOptions = []
                const optionMap = this.voteOptionMap && Object.keys(this.voteOptionMap).length > 0 ? 
                    this.voteOptionMap : this.groupedOptions
                
                // 直接遍历所有选项，找出所有选中的选项
                Object.values(optionMap).forEach(options => {
                    const questionSelectedOptions = options.filter(item => 
                        this.selectedOptionIds.includes(String(item.optionId))
                    )
                    selectedOptions = selectedOptions.concat(questionSelectedOptions)
                })
                return selectedOptions
            } 
            // 单问题模式
            else {
                if (this.isRadio) {
                    const rows = this.voteOptions.filter((item, key) => this.selectedIndex.includes(key))
                    return rows
                } else {
                    let row = this.voteOptions.find((item, key) => key == this.selectedIndex[0])
                    return [row]
                }
            }
        },
        // 多问题模式选择处理
        handleSelect(idx, questionTitle) {
            // 如果是重新投票，禁用选项修改
            if (this.isRevote) {
                return
            }
            
            if (this.isVotingInfo.status == 1 && !this.isVotingInfo.isVoting) {
                const optionMap = this.voteOptionMap && Object.keys(this.voteOptionMap).length > 0 ? 
                    this.voteOptionMap : this.groupedOptions
                const options = optionMap[questionTitle] || []
                const selectedOption = options[idx]
                
                if (selectedOption) {
                    // 获取当前问题的选择类型
                    const isMultiSelect = this.getQuestionSelectType(questionTitle)
                    
                    if (isMultiSelect) {
                        // 多选逻辑：可以同时选择多个选项
                        const optionId = String(selectedOption.optionId)
                        const currentQuestionSelected = this.selectedOptionsByQuestion[questionTitle] || []
                        
                        if (currentQuestionSelected.includes(optionId)) {
                            // 已选中则取消
                            const index = currentQuestionSelected.indexOf(optionId)
                            currentQuestionSelected.splice(index, 1)
                        } else {
                            // 未选中则添加 - 检查max限制
                            const questionLimit = this.getQuestionSelectionLimit(questionTitle)
                            if (currentQuestionSelected.length >= questionLimit.max) {
                                // 已达到最大选择数量
                                this.showSelectionLimitToast(questionTitle, questionLimit.max, 'max')
                                return
                            }
                            currentQuestionSelected.push(optionId)
                        }
                        
                        this.$set(this.selectedOptionsByQuestion, questionTitle, currentQuestionSelected)
                    } else {
                        // 单选逻辑：只清空当前问题的选择，不影响其他问题
                        this.$set(this.selectedOptionsByQuestion, questionTitle, [String(selectedOption.optionId)])
                    }
                    
                    // 更新全局选中选项ID数组
                    this.updateSelectedOptionIds()
                    
                    // 传递选中的选项
                    const selectedItems = this.getSelectedIndex()
                    this.$emit("input", selectedItems)
                }
            }
        },
        // 单问题模式选择处理
        handleSelectSingle(idx) {
            // 如果是重新投票，禁用选项修改
            if (this.isRevote) {
                return
            }
            
            if (this.isVotingInfo.status == 1 && !this.isVotingInfo.isVoting) {
                if (this.isRadio) {
                    // 多选
                    const index = this.selectedIndex.indexOf(idx)
                    if (index > -1) {
                        // 已选中则取消
                        this.selectedIndex.splice(index, 1)
                    } else {
                        // 未选中则添加
                        this.selectedIndex.push(idx)
                    }
                    // 传递所有选中的 optionId
                    const selectedItems = this.voteOptions.filter((item, key) => this.selectedIndex.includes(key))
                    this.$emit("input", selectedItems)
                } else {
                    // 单选
                    let row = this.voteOptions.find((item, key) => key == idx)
                    this.selectedIndex = [idx]
                    this.$emit("input", [row])
                }
            }
        },
        // 更新全局选中选项ID数组
        updateSelectedOptionIds() {
            this.selectedOptionIds = []
            Object.keys(this.selectedOptionsByQuestion).forEach(questionTitle => {
                const questionSelectedIds = this.selectedOptionsByQuestion[questionTitle] || []
                this.selectedOptionIds = this.selectedOptionIds.concat(questionSelectedIds)
            })
        },

        // 获取议题的选择限制（min/max）
        getQuestionSelectionLimit(questionTitle) {
            // 优先从 groupedOptions 中获取（包含 mock 数据）
            if (this.groupedOptions && this.groupedOptions[questionTitle]) {
                const options = this.groupedOptions[questionTitle]
                if (options && options.length > 0) {
                    // 取第一个选项的 min/max 值（同一议题的所有选项应该有相同的限制）
                    const firstOption = options[0]
                    return {
                        min: firstOption.min || 0,
                        max: firstOption.max || 999
                    }
                }
            }
            
            // 回退到 voteOptions
            if (this.voteOptions && this.voteOptions.length > 0) {
                const questionOption = this.voteOptions.find(option => 
                    option.title === questionTitle || option.questionTitle === questionTitle
                )
                
                if (questionOption) {
                    return {
                        min: questionOption.min || 0,
                        max: questionOption.max || 999
                    }
                }
            }
            
            return { min: 0, max: 999 }
        },

        // 显示选择限制提示
        showSelectionLimitToast(questionTitle, limit, type) {
            let message = ''
            if (type === 'max') {
                message = `该议题最多只能选择${limit}个选项`
            } else if (type === 'min') {
                message = `该议题至少需要选择${limit}个选项`
            }
            
            uni.showToast({
                title: message,
                icon: 'none',
                duration: 2000
            })
        },

        // 判断是否应该显示限制提示
        shouldShowLimitHint(questionTitle) {
            const isMultiSelect = this.getQuestionSelectType(questionTitle)
            
            // 单选问题不显示限制提示
            if (!isMultiSelect) {
                return false
            }
            
            const limit = this.getQuestionSelectionLimit(questionTitle)
            // 多选问题最基础的限制：至少选择1个
            const minRequired = Math.max(limit.min, 1)
            
            // 如果min=1且max=999，表示只有基础限制，不显示提示
            if (minRequired === 1 && limit.max === 999) {
                return false
            }
            
            return true
        },

        // 获取限制提示文本
        getLimitHintText(questionTitle) {
            const limit = this.getQuestionSelectionLimit(questionTitle)
            // 多选问题最基础的限制：至少选择1个
            const minRequired = Math.max(limit.min, 1)
            
            // 固定数量
            if (minRequired === limit.max) {
                return `固定选择${minRequired}个`
            }
            
            // 只有下限
            if (minRequired > 1 && limit.max === 999) {
                return `至少选择${minRequired}个`
            }
            
            // 只有上限
            if (minRequired === 1 && limit.max < 999) {
                return `最多选择${limit.max}个`
            }
            
            // 有下限和上限
            if (minRequired > 1 && limit.max < 999) {
                return `至少选择${minRequired}个，最多选择${limit.max}个`
            }
            
            return ''
        },
        
        // 获取问题的文件URL
        getQuestionFileUrl(questionTitle) {
            if (this.groupedOptions && this.groupedOptions[questionTitle]) {
                const options = this.groupedOptions[questionTitle]
                console.log("options",options)
                if (options && options.length > 0) {
                    return options[0].fileUrl || ''
                }
            }
            return ''
        }
    }
}
</script>
<style lang="scss" scoped>

.vote-from-title{
    border-radius: 8rpx;
            border: 1rpx solid rgba(155,142,142,0.5);
            padding: 12rpx 18rpx;
            margin-bottom: 20rpx;
           }
.vote-from{
    width: 100%;
    height: 100%;
    background: #fff;
    border-radius: 18rpx;
    padding:30rpx 20rpx ;
    margin: 0 4rpx;
    box-shadow: 0rpx 0rpx 27rpx 0rpx rgba(0,0,0,0.03);
   margin-top: 20rpx;
    border-radius: 16rpx ;
    display: flex;
    flex-direction: column;
    justify-content:center;
    align-items: center;
        &-content{
           width: 100%;
           margin-bottom: 30rpx;
           &:last-child {
               margin-bottom: 0;
           }
           &-title{
            font-weight: 600;
            font-size: 30rpx;
            color: #000000;
            margin-bottom: 20rpx;
            padding: 10rpx 0;
            border-bottom: 1rpx solid #f0f0f0;
            .selection-limit-hint {
                font-weight: 400;
                font-size: 24rpx;
                color: #999;
                margin-left: 8rpx;
            }
           }

           &-item{
            width: 100%;
            margin-top: 20rpx;
         
           }
        }
        .no-data {
            text-align: center;
            color: #999;
            padding: 40rpx;
        }
    
}
</style>
